package com.zbbt.sportslottery.ui.fragment;

import java.util.ArrayList;
import java.util.List;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.gc.materialdesign.views.ButtonRectangle;
import com.gc.materialdesign.views.ProgressBarCircularIndetermininate;
import com.google.gson.JsonObject;
import com.zbbt.sportslottery.R;
import com.zbbt.sportslottery.app.App;
import com.zbbt.sportslottery.app.ServerConfig;
import com.zbbt.sportslottery.bean.DialogBean.OnDialogClickListener;
import com.zbbt.sportslottery.bean.LotteryShopData;
import com.zbbt.sportslottery.bean.SuperResult;
import com.zbbt.sportslottery.net.TypeGsonHttpHandler;
import com.zbbt.sportslottery.net.ZbHttpClient;
import com.zbbt.sportslottery.ui.activity.LotteryShopMapActivity;
import com.zbbt.sportslottery.ui.adapter.LotteryShopAdapter;
import com.zbbt.sportslottery.ui.widget.SimpleCustomDialog;
import com.zbbt.sportslottery.ui.widget.swipe.SwipeRefreshLayout;
import com.zbbt.sportslottery.ui.widget.swipe.SwipeRefreshLayout.OnRefreshListener;
import com.zbbt.sportslottery.util.DialogUtil;
import com.zbbt.sportslottery.util.LogUtil;
import com.zbbt.sportslottery.util.ToastUtil;

public class LotteryShopFragment extends BaseMenuFragment {
	/* 地图的定位——————明硕* */
	private LocationClient location;
	private MyLocationListenner myLocationListenner = new MyLocationListenner();
	private Double Longitude = 0.0;// 定位获取经度
	private Double Latitude = 0.0;// 定位获取纬度
	private boolean isFirstLoc = true;// 是否首次定位
	private TextView exception_tx;
	private int page_number = 1;
	private int page_size = 10;
	private LotteryShopAdapter mAdapter;
	private SwipeRefreshLayout refreshLayout;
	private ListView mListView;
	private ProgressBarCircularIndetermininate progressBar;
	private List<LotteryShopData> shopDatas = new ArrayList<LotteryShopData>();
	private boolean isShow = false;// 是否显示
	private boolean isGetMore = false;// 请求形式，true=翻页／false=当前页
	private boolean hasMore = true;// 是否还有下一页
	private boolean isOnPause = false;// 是否显离开本页
	private boolean isHttpFinish = true;// 是否完成一次网络请求
	private LinearLayout error_linear;

	public static LotteryShopFragment getInstance() {
		return new LotteryShopFragment();
	}

	@Override
	protected void initView(LayoutInflater inflater) {
		mView = inflater.inflate(R.layout.fragment_lottry_shop, null);
		progressBar = (ProgressBarCircularIndetermininate) findViewById(R.id.progressBarCircularIndetermininate);
		// 初始化视图
		refreshLayout = (SwipeRefreshLayout) mView.findViewById(R.id.lottry_swipe_container);
		mListView = (ListView) findViewById(R.id.notice_listview);
		exception_tx = (TextView) findViewById(R.id.exception_tx);
		error_linear=(LinearLayout) findViewById(R.id.error_layout);
		mAdapter = new LotteryShopAdapter(context, shopDatas);
		mAdapter.setOnBottomClickListener(new LotteryShopAdapter.OnBottomClickListener() {

			@Override
			public void onBottomClick() {
				if (hasMore == true) {
					page_number++;
					isGetMore = true;
					initData();
					refreshLayout.setRefreshing(true);
				}
			}
		});
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent intent = new Intent(getActivity(), LotteryShopMapActivity.class);
				LotteryShopData lotteryShopData = shopDatas.get(position);
				String address = lotteryShopData.getAddress();// 地址
				String coordinate = lotteryShopData.getLatitude() + "," + lotteryShopData.getLongitude();// 坐标
				intent.putExtra("address", address);
				intent.putExtra("coordinate", coordinate);
				startActivity(intent);
			}
		});

		refreshLayout.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				if (isHttpFinish) {
					page_number = 1;
					isGetMore = false;
					initLocData();
					exception_tx.setVisibility(View.GONE);
				}
			}

		});
		progressBar.setVisibility(View.VISIBLE);

	}

	@Override
	public void onResume() {
		super.onResume();
		isOnPause = false;
		if (App.isLotteryShopFragment) {
			// 定位初始化
			initLocData();
			progressBar.setVisibility(View.VISIBLE);
			exception_tx.setVisibility(View.GONE);
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		if (location != null) {
			location.stop();
		}
		App.isLotteryShopFragment = false;
		isOnPause = true;
		progressBar.setVisibility(View.GONE);

	}

	/**
	 * 
	 * @MethodName:initLocData
	 * @Description: 定位初始化后，两秒后判断经纬度有没拿到。没拿到弹窗，拿到请求服务器
	 * @author：gaomingshuo
	 * @date：2015-1-23 下午3:00:17 void
	 */

	public void initLocData() {
		shopDatas.clear();
		mAdapter.notifyDataSetChanged();
		isHttpFinish = false;
		initLoc();
		new Handler().postDelayed(new Runnable() {
			public void run() {
				whetherHave();
			}
		}, 3000);
	}

	/**
	 * 
	 * @MethodName:initLoc
	 * @Description: TODO
	 * @author：gaomingshuo
	 * @date：2015-1-23 下午3:00:00 void
	 */
	public void initLoc() {
		isFirstLoc = true;
		location = new LocationClient(getActivity());
		location.registerLocationListener(myLocationListenner);
		LocationClientOption option = new LocationClientOption();// 打开经纬度坐标
		option.setLocationMode(LocationMode.Hight_Accuracy);// 高精度模式
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(1000);
		location.setLocOption(option);
		location.start();
	}

	/**
	 * 
	 * @MethodName:whetherHave
	 * @Description: TODO
	 * @author：gaomingshuo
	 * @date：2015-1-23 下午2:59:29 void
	 */
	public void whetherHave() {
		if (Latitude == 4.9E-324 || Latitude == 0.0) {
			progressBar.setVisibility(View.GONE);
			if (isShow == false) {
				if (!isOnPause) {
					initLocation();// 提示弹窗
				} else {
					// 直接跳转Activity（LoginActivity），会执行
					exception_tx.setVisibility(View.VISIBLE);
					exception_tx.setText("请下拉刷新");
				}
			} else {
				exception_tx.setVisibility(View.VISIBLE);// 提示打开软件
				exception_tx.setText("位置还是无法获取?查看是否被安全软件关闭权限或者重新打开软件");
			}
			isHttpFinish = true;
			progressBar.setVisibility(View.GONE);
			refreshLayout.setRefreshing(false);
		} else {
			initData();
			exception_tx.setVisibility(View.GONE);
		}
	}

	/**
	 * 
	 * @MethodName: initLocation
	 * @Description: 没拿到经纬度，弹窗提示
	 * @author: gaomingshou
	 * @date: 2015年1月23日 下午14:31:98
	 */
	private void initLocation() {
		SimpleCustomDialog showConfirmDialog = DialogUtil.showConfirmDialog(context, "提示",
				"查看网点需要开启GPS，确定是否开启", "去设置", "已开启", new OnDialogClickListener() {

					@Override
					public boolean onClick(View v) {
						Intent callGPSSettingIntent = new Intent(
								android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
						startActivity(callGPSSettingIntent);
						isShow = true;
						exception_tx.setVisibility(View.VISIBLE);
						exception_tx.setText("确定GPS已开启，下拉刷新");
						return false;
					}
				}, new OnDialogClickListener() {

					@Override
					public boolean onClick(View v) {
						isShow = true;
						progressBar.setVisibility(View.VISIBLE);
						initLocData();
						if (!(Latitude == 4.9E-324 || Latitude == 0.0)) {
							initData();
						}
						return false;
					}
				});
		// 当点击弹窗空白的时候给出的提示。
		showConfirmDialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				exception_tx.setVisibility(View.VISIBLE);
				exception_tx.setText("请下拉刷新");
			}
		});

	}

	@Override
	protected void setListener() {
		error_linear.setOnClickListener(this);
	}

	@Override
	protected void onClickEvent(View v) {
		switch (v.getId()) {
		case R.id.error_layout:
			progressBar.setVisibility(View.VISIBLE);
			error_linear.setVisibility(View.GONE);
			initLocData();
			exception_tx.setVisibility(View.GONE);
			break;

		default:
			break;
		}
	}

	@Override
	protected void initData() {
		JsonObject jsonObject = new JsonObject();
		String coordinateStr = Longitude + "," + Latitude;
		jsonObject.addProperty("coordinate", coordinateStr);
		jsonObject.addProperty("curPage", page_number);
		jsonObject.addProperty("pageSize", page_size);
		jsonObject.addProperty("ticketType", 1);
		jsonObject.addProperty("distance", 10000000.0);
		LogUtil.printD("DemoLog", coordinateStr);
		ZbHttpClient.postNewApi(ServerConfig.API_TZZD, jsonObject,
				new TypeGsonHttpHandler<SuperResult<LotteryShopData>>(true) {
					@Override
					public void onSuccess(SuperResult<LotteryShopData> data) {
						isHttpFinish = true;
						progressBar.setVisibility(View.GONE);
						ArrayList<LotteryShopData> data2 = data.getData();
						if (data2.size() == 0) {
							refreshLayout.setRefreshing(false);
							ToastUtil.showShort("没有数据");
							error_linear.setVisibility(View.VISIBLE);
							return;
						}
						if (data.getData() != null) {
							if (!isGetMore) {
								shopDatas.clear();
							}
							shopDatas.addAll(data.getData());
							mAdapter.notifyDataSetChanged();
							refreshLayout.setRefreshing(false);
						} else {
							hasMore = false;
						}
					}

					@Override
					public void onFailure(String errorCode, String errorMsg) {
						isHttpFinish = true;
						progressBar.setVisibility(View.GONE);
						refreshLayout.setRefreshing(false);
						// shopDatas.clear();
						error_linear.setVisibility(View.VISIBLE);
						ToastUtil.showShort("服务器异常，请检查网络");
					}
				});
	}

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (isFirstLoc) {
				// 首次定位，拿到经度纬度
				isFirstLoc = false;
				Latitude = location.getLatitude();
				Longitude = location.getLongitude();
				LogUtil.printI(TAG, "经度" + Latitude + "===纬度" + Longitude);

			}
		}
	}

}
